package com.funnyx.config;

import com.funnyx.service.ZkLockService;
import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
public class ZookeeperProp {

  @Value("${curator.retryCount}")
  private int retryCount;

  @Value("${curator.elapsedTimeMs}")
  private int elapsedTimeMs;

  @Value("${curator.connectURL}")
  private String connectURL;

  @Value("${curator.sessionTimeoutMs}")
  private int sessionTimeoutMs;

  @Value("${curator.connectionTimeoutMs}")
  private int connectionTimeoutMs;

  @Bean(initMethod = "start", destroyMethod = "close")
  public CuratorFramework curator() {
    CuratorFramework curatorFramework =
        CuratorFrameworkFactory.newClient(
            connectURL,
            sessionTimeoutMs,
            connectionTimeoutMs,
            new RetryNTimes(retryCount, elapsedTimeMs));
    return curatorFramework;
  }

  @Bean
  @ConditionalOnProperty(name = "zklock.enable", havingValue = "true")
  public ZkLockService zkLockService() {
    return new ZkLockService();
  }
}
